<template>
  <el-dialog
    :title="$t('message.excel.roleDialogTitle')"
    :model-value="modelValue"
    @close="close"
  >
    <!-- 分配权限 -->
    <el-tree
      ref="treeRef"
      :data="allPermissionList"
      show-checkbox
      check-strictly
      node-key="id"
      default-expand-all
      :props="defaultProps"
    />
    <template #footer>
      <el-button @click="close">{{ $t('message.universal.cancel') }}</el-button>
      <el-button @click="confirm" type="primary">
        {{ $t('message.universal.confirm') }}
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, defineEmits, defineProps, watch } from 'vue'
import { watchLangChange } from '@/utils/i18n'
import {
  rolePermission,
  permissionList,
  pushPermission
} from '@/api/permission'
import { ElMessage } from 'element-plus'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String
  }
})

const emits = defineEmits(['update:modelValue'])
const confirm = async () => {
  await saveUserPermission()
  ElMessage.success('保存成功')
  close()
}
const close = () => {
  emits('update:modelValue', false)
}
const checkedKeys = ref([])
watch(
  () => props.roleId,
  async () => {
    checkedKeys.value = await rolePermission(props.roleId)
    setChecked()
  }
)
// 获取所有权限
const allPermissionList = ref([])
const getPermissionList = async () => {
  const resp = await permissionList()
  allPermissionList.value = resp
}
watchLangChange(getPermissionList)
getPermissionList()
const defaultProps = {
  children: 'children',
  label: 'permissionName'
}
const treeRef = ref(null)
const setChecked = () => {
  treeRef.value.setCheckedKeys(checkedKeys.value)
}
// 保存用户权限
const saveUserPermission = async () => {
  const checkedNodes = treeRef.value.getCheckedKeys()
  const checkedKeys = checkedNodes
  await pushPermission(props.roleId, checkedKeys)
}
</script>
<style less="scss"></style>
